<template>
  <div class="register-container">
    <div class="card">
      <h2 class="title">用户注册</h2>
      <form @submit.prevent="submitForm" class="form">
        <div class="form-group">
          <label for="email">邮箱：</label>
          <div class="email-input-group">
            <input
              type="email"
              id="email"
              v-model="formData.email"
              required
              placeholder="请输入邮箱"
            />
            <button 
              type="button" 
              @click="sendCode" 
              :disabled="countdown > 0 || !formData.email"
              class="send-code-btn"
            >
              {{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
            </button>
          </div>
        </div>
        
        <div class="form-group">
          <label for="code">验证码：</label>
          <input
            type="text"
            id="code"
            v-model="formData.code"
            required
            placeholder="请输入验证码"
            maxlength="6"
          />
        </div>
        
        <div class="form-group">
          <label for="username">用户名：</label>
          <input
            id="username"
            v-model="formData.username"
            required
            placeholder="请输入用户名"
          />
        </div>
        
        <div class="form-group">
          <label for="password">密码：</label>
          <input
            type="password"
            id="password"
            v-model="formData.password"
            required
            placeholder="请输入密码"
          />
        </div>
        
        <div class="form-group">
          <label for="confirmPassword">确认密码：</label>
          <input
            type="password"
            id="confirmPassword"
            v-model="confirmPassword"
            required
            placeholder="请再次输入密码"
          />
        </div>
        
        <div class="button-group">
          <button type="submit" class="register-button" :disabled="isSubmitting">
            {{ isSubmitting ? '注册中...' : '注册' }}
          </button>
          <button type="button" class="back-button" @click="goToLogin">返回登录</button>
        </div>
        <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
        <p v-if="successMessage" class="success-message">{{ successMessage }}</p>
      </form>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Register',
  data() {
    return {
      formData: {
        email: '',
        code: '',
        password: '',
        username: ''
      },
      confirmPassword: '',
      errorMessage: '',
      successMessage: '',
      countdown: 0,
      isSubmitting: false
    };
  },
  methods: {
    async sendCode() {
      if (!this.formData.email) {
        this.errorMessage = '请先输入邮箱';
        return;
      }
      
      // 立即开始倒计时，防止重复点击
      this.startCountdown();
      
      try {
        const response = await axios.post('http://localhost:9527/users/send-code', {
          email: this.formData.email
        });
        
        this.successMessage = '验证码已发送，请查收邮箱';
        this.errorMessage = '';
        
        // 3秒后清除成功消息
        setTimeout(() => {
          this.successMessage = '';
        }, 3000);
        
      } catch (error) {
        console.error('发送验证码失败:', error);
        // 显示具体的错误信息
        if (error.response && error.response.status === 400) {
          this.errorMessage = error.response.data || '发送失败，请稍后重试';
        } else {
          this.errorMessage = '发送失败，请稍后重试';
        }
        this.successMessage = '';
        // 发送失败时重置倒计时，允许重新发送
        this.countdown = 0;
      }
    },
    
    startCountdown() {
      this.countdown = 60;
      const timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
    
    async submitForm() {
      if (this.formData.password !== this.confirmPassword) {
        this.errorMessage = '两次输入的密码不一致，请重新输入。';
        return;
      }
      
      if (!this.formData.code) {
        this.errorMessage = '请输入验证码';
        return;
      }
      
      this.isSubmitting = true;
      this.errorMessage = '';
      
      try {
        const response = await axios.post('http://localhost:9527/users/register', this.formData);
        
        this.successMessage = '注册成功！正在跳转到登录页面...';
        this.errorMessage = '';
        
        // 3秒后跳转到登录页面
        setTimeout(() => {
          this.$router.push('/login');
        }, 3000);
        
      } catch (error) {
        console.error('注册失败:', error);
        this.errorMessage = error.response?.data || '注册失败，请检查输入或稍后再试。';
        this.successMessage = '';
      } finally {
        this.isSubmitting = false;
      }
    },
    
    resetForm() {
      this.formData = {
        email: '',
        code: '',
        password: '',
        username: ''
      };
      this.confirmPassword = '';
      this.errorMessage = '';
      this.successMessage = '';
    },
    
    goToLogin() {
      this.$router.push('/login');
    }
  }
};
</script>


<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');

.register-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #d0eaff, #f0f8ff);
  padding: 20px;
  font-family: 'Roboto', sans-serif;
}

.card {
  background-color: #ffffff;
  padding: 30px 40px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  max-width: 440px;
  width: 100%;
  box-sizing: border-box;
  transition: all 0.3s ease;
}

.title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 2rem;
  color: #165DFF;
  font-weight: 700;
}

.form {
  display: flex;
  flex-direction: column;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #333;
}

input {
  width: 100%;
  padding: 10px 14px;
  border: 1px solid #ccc;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.2s;
}

input:focus {
  border-color: #165DFF;
  outline: none;
}

.email-input-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.email-input-group input {
  flex: 1;
}

.send-code-btn {
  background-color: #165DFF;
  color: #fff;
  border: none;
  padding: 10px 14px;
  border-radius: 8px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: background-color 0.2s;
  white-space: nowrap;
  min-width: 100px;
}

.send-code-btn:hover:not(:disabled) {
  background-color: #0f4c8a;
}

.send-code-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.button-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 15px;
}

.register-button {
  background-color: #42b983;
  color: #fff;
  border: none;
  padding: 12px;
  border-radius: 8px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.2s, transform 0.2s;
}

.register-button:hover {
  background-color: #369c6b;
  transform: scale(1.02);
}

.back-button {
  background-color: transparent;
  border: 2px solid #165DFF;
  color: #165DFF;
  padding: 11px;
  border-radius: 8px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s;
}

.back-button:hover {
  background-color: #165DFF;
  color: #fff;
  transform: scale(1.02);
}

.error-message {
  margin-top: 10px;
  color: red;
  font-size: 0.9rem;
  text-align: center;
}

.success-message {
  margin-top: 10px;
  color: #42b983;
  font-size: 0.9rem;
  text-align: center;
}
</style>